package cn.tianyue0571.brunning;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.LocationSource;

import cn.tianyue0571.brunning.base.AbsBaseActivity;
import cn.tianyue0571.brunning.inject.FindView;
import cn.tianyue0571.brunning.inject.OnClick;
import cn.tianyue0571.brunning.stepcount.StepCountService;
import cn.tianyue0571.brunning.stepcount.UpdateUiCallBack;
import cn.tianyue0571.brunning.util.permission.MPermission;
import cn.tianyue0571.brunning.util.permission.annotation.OnMPermissionDenied;
import cn.tianyue0571.brunning.util.permission.annotation.OnMPermissionGranted;
import cn.tianyue0571.brunning.util.permission.annotation.OnMPermissionNeverAskAgain;

public class RunningActivity extends AbsBaseActivity implements LocationSource, AMapLocationListener {
    @FindView(R.id.tv_title)
    TextView mTitle;
    private final int LOCATION_REQUEST_CODE = 0x133;
    @FindView(R.id.m_btn_start_1)
    LinearLayout mLayoutStart;
    @FindView(R.id.m_btn_stop_1)
    LinearLayout mLayoutStop;
    @FindView(R.id.m_btn_pause_1)
    LinearLayout mLayoutPause;
    @FindView(R.id.tv_step_count)
    TextView mTvStepCount;
    private boolean isBind = false;
    /**
     * 用于查询应用服务（application Service）的状态的一种interface，
     * 更详细的信息可以参考Service 和 context.bindService()中的描述，
     * 和许多来自系统的回调方式一样，ServiceConnection的方法都是进程的主线程中调用的。
     */
    ServiceConnection conn = new ServiceConnection() {
        /**
         * 在建立起于Service的连接时会调用该方法，目前Android是通过IBind机制实现与服务的连接。
         * @param name 实际所连接到的Service组件名称
         * @param service 服务的通信信道的IBind，可以通过Service访问对应服务
         */
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            StepCountService stepService = ((StepCountService.StepBinder) service).getService();
            //设置初始化数据
//            String planWalk_QTY = (String) sp.getParam("planWalk_QTY", "7000");
//            cc.setCurrentCount(Integer.parseInt(planWalk_QTY), stepService.getStepCount());
            mTvStepCount.setText(stepService.getStepCount() + "步");
            //设置步数监听回调
            stepService.registerCallback(new UpdateUiCallBack() {
                @Override
                public void updateUi(int stepCount) {
                    //todo
                    mTvStepCount.setText(stepCount + "步");
                }
            });
        }

        /**
         * 当与Service之间的连接丢失的时候会调用该方法，
         * 这种情况经常发生在Service所在的进程崩溃或者被Kill的时候调用，
         * 此方法不会移除与Service的连接，当服务重新启动的时候仍然会调用 onServiceConnected()。
         * @param name 丢失连接的组件名称
         */
        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_running;
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mTitle.setText("跑步");
        initGPS();
        requestLocationPermission();
        mTvStepCount.setText("0步");
        setupService();
    }

    /**
     * 开启计步服务
     */
    private void setupService() {
        Log.d(TAG, "-----------begin-----------");
        Intent intent = new Intent(this, StepCountService.class);
        isBind = bindService(intent, conn, Context.BIND_AUTO_CREATE);
        startService(intent);
    }

    private void requestLocationPermission() {
        MPermission.with(this)
                .addRequestCode(LOCATION_REQUEST_CODE)
                .permissions(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.READ_PHONE_STATE
                )
                .request();
    }

    @OnMPermissionGranted(LOCATION_REQUEST_CODE)
    public void onLocationSuccess() {
        setupService();
    }

    @OnMPermissionDenied(LOCATION_REQUEST_CODE)
    public void onLocationFailed() {

    }

    @OnMPermissionNeverAskAgain(LOCATION_REQUEST_CODE)
    public void onLocationNeverAskAgain() {

    }

    private void initGPS() {
        LocationManager locationManager = (LocationManager) this
                .getSystemService(Context.LOCATION_SERVICE);
        // 判断GPS模块是否开启，如果没有则开启
        if (!locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER)) {
//            Toast.makeText(this, "请打开GPS",
//                    Toast.LENGTH_SHORT).show();
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setMessage("为了获得更准确的运动记录，请打开GPS");
            dialog.setPositiveButton("确定",
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {

                            // 转到手机设置界面，用户设置GPS
                            Intent intent = new Intent(
                                    Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, 0); // 设置完成后返回到原来的界面

                        }
                    });
            dialog.setNeutralButton("取消", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    arg0.dismiss();
                }
            });
            dialog.show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    /**
     * 开始记录轨迹,开始记录本次跑步数,
     */
    public void biginToTrack() {

    }

    /**
     * 暂停记录轨迹
     */
    public void pauseToTrack() {

    }

    /**
     * 停止记录轨迹
     */
    public void stopToTrack() {

    }

    @OnClick({R.id.m_goto_map, R.id.m_btn_start, R.id.m_btn_stop, R.id.m_btn_pause})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.m_goto_map:
                startActivity(new Intent(this, ShowMapTrackActivity.class));
                break;
            case R.id.m_btn_start:
                mLayoutStart.setVisibility(View.GONE);
                mLayoutPause.setVisibility(View.VISIBLE);
                mLayoutStop.setVisibility(View.GONE);
                break;
            case R.id.m_btn_stop:
                mLayoutStart.setVisibility(View.VISIBLE);
                mLayoutPause.setVisibility(View.GONE);
                mLayoutStop.setVisibility(View.VISIBLE);
                break;
            case R.id.m_btn_pause:
                mLayoutStart.setVisibility(View.VISIBLE);
                mLayoutPause.setVisibility(View.GONE);
                mLayoutStop.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {

    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {

    }

    @Override
    public void deactivate() {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (isBind) {
            this.unbindService(conn);
        }
    }
}
